import {Component, OnInit} from '@angular/core';
import {NzFormatEmitEvent, NzTreeNodeOptions} from 'ng-zorro-antd/tree';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {HttpErrorResponse} from '@angular/common/http';
import {EquipMainDataHttpServices} from '../http/http';
import {NzUploadChangeParam, NzUploadFile} from 'ng-zorro-antd/upload';

interface DeviceInstanceTableItem {
  code: string;
  name: string;
  deviceDefName: string;
  deviceDefId: number;
  model: string;
  createUserName: string;
  createTime: string;
  id?: number;
  imageUrl: string;
}

@Component({
  selector: 'app-equip-device-instance',
  styleUrls: ['./components.less'],
  template: `
    <div class="device-instance-container">
      <div class="device-instance-left">
        <nz-tree [nzData]="nodes" (nzClick)="nzEvent($event)" (nzExpandChange)="nzEvent($event)" nzAsyncData></nz-tree>
      </div>
      <div class="device-instance-right" *ngIf="currentParams.siteId || currentParams.attrId">
        <div class="equipMainDataMgmtContainer">
          <div class="device-instance-bar">
            <button nz-button style="background:'green';color:'#ffffff';border-color: 'transparent'"
                    (click)="visibleObject.formVisible = true">新增
            </button>
          </div>
          <nz-table #deviceInstanceTable [nzShowSizeChanger]="true" [nzShowQuickJumper]="true"
                    [nzData]="tableData" [nzLoading]="loading" [nzFrontPagination]="false"
                    [nzTotal]="pagination.total" [(nzPageSize)]="pagination.size" [(nzPageIndex)]="pagination.start"
                    (nzPageIndexChange)="pagination.start = $event;loadTable()"
                    (nzPageSizeChange)="pagination.size = $event;loadTable()">
            <thead>
            <tr>
              <th>编码</th>
              <th>名称</th>
              <th>设备定义</th>
              <th>设备型号</th>
              <th>创建人</th>
              <th>创建时间</th>
              <th nzAlign="center">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr *ngFor="let defItem of deviceInstanceTable.data">
              <td>{{ defItem.code }}</td>
              <td>{{ defItem.name }}</td>
              <td>{{ defItem.deviceDefName }}</td>
              <td>{{ defItem.model }}</td>
              <td>{{ defItem.createUserName }}</td>
              <td>{{ defItem.createTime }}</td>
              <td class='option-td' nzAlign="center">
                <span (click)="onEdit(defItem)">修改</span>
                <span (click)="editData = defItem;visibleObject.deleteVisible = true">删除</span>
                <span (click)="editData = defItem; visibleObject.imageVisible = true">查看图片</span>
              </td>
            </tr>
            </tbody>
          </nz-table>
        </div>

        <nz-modal [(nzVisible)]="visibleObject.formVisible" [nzTitle]="modalTitle" (nzOnCancel)="visibleObject.formVisible = false"
                  (nzOnOk)="handleSubmit()" [nzWidth]="744">
          <ng-template #modalTitle>{{mode === 'create' ? '新增' : '修改'}}属性定义</ng-template>
          <ng-container *nzModalContent>
            <form nz-form [formGroup]="deviceInstanceForm" class="attr-type-form">
              <nz-form-item>
                <nz-form-label nzRequired [nzSpan]="8">
                  编码
                </nz-form-label>
                <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
                  <input nz-input formControlName="code"/>
                </nz-form-control>
              </nz-form-item>
              <nz-form-item>
                <nz-form-label nzRequired [nzSpan]="8">
                  名称
                </nz-form-label>
                <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
                  <input nz-input formControlName="name"/>
                </nz-form-control>
              </nz-form-item>
              <nz-form-item>
                <nz-form-label nzRequired [nzSpan]="8">
                  设备定义
                </nz-form-label>
                <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
                  <nz-select formControlName="deviceDefId">
                    <nz-option *ngFor=" let i of deviceDefAllData" [nzLabel]="i.name" [nzValue]="i.id"></nz-option>
                  </nz-select>
                </nz-form-control>
              </nz-form-item>
              <nz-form-item>
                <nz-form-label nzRequired [nzSpan]="8">
                  设备型号
                </nz-form-label>
                <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
                  <input nz-input formControlName="model">
                </nz-form-control>
              </nz-form-item>
              <nz-form-item>
                <nz-form-label nzRequired [nzSpan]="8">
                  图片
                </nz-form-label>
                <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
                  <input nz-input formControlName="imageUrl" *ngIf="false"/>
                  <nz-upload
                    [nzAction]="this.http.getApiList().UPLOAD_IMG"
                    (nzChange)="handleChange($event)"
                    nzAccept="image/png, image/jpeg"
                    [(nzFileList)]="fileList"
                    [nzData]="getExtraData"
                    nzListType="picture"
                  >
                    <button nz-button><i nz-icon nzType="upload"></i>Click to Upload</button>
                  </nz-upload>
                </nz-form-control>
              </nz-form-item>
            </form>
          </ng-container>
        </nz-modal>
      </div>
    </div>

    <nz-modal [(nzVisible)]="visibleObject.deleteVisible" nzTitle="警告" (nzOnCancel)="visibleObject.deleteVisible = false"
              (nzOnOk)="onDelete()">
      <ng-container *nzModalContent>
        您确认要删除此项吗？
      </ng-container>
    </nz-modal>

    <nz-modal [(nzVisible)]="visibleObject.imageVisible" nzTitle="查看图片" (nzOnCancel)="visibleObject.imageVisible = false"
              (nzOnOk)="visibleObject.imageVisible = false" [nzWidth]="600">
      <ng-container *nzModalContent style="text-align: center">
        <img [src]="getImageUrl(editData.imageUrl)" *ngIf="editData" alt="" [width]="560"/>
      </ng-container>
    </nz-modal>
  `
})


export class DeviceInstanceMgmtComponent implements OnInit {
  constructor(private http: EquipMainDataHttpServices, private fb: FormBuilder) {
  }

  fileList: Array<NzUploadFile>;
  deviceInstanceForm!: FormGroup;
  visibleObject = {
    deleteVisible: false,
    formVisible: false,
    imageVisible: false,
  };
  pagination = {
    start: 1,
    size: 10,
    total: 0
  };
  loading = false;
  deviceDefAllData: any;
  tableData!: Array<DeviceInstanceTableItem>;
  editData !: DeviceInstanceTableItem;
  mode = 'create';
  nodes = [];
  currentParams = {
    siteId: null,
    attrId: null
  };

  getImageUrl(imageName: string): string {
    const aplList = this.http.getApiList();
    return `http://${aplList.GET_IMG}${imageName}`;
  }

  onDelete(): void {
    const {id} = this.editData;
    this.http.deleteDeviceInstance({id}).subscribe(
      (response) => {
        if (response.code === 0) {
          this.loadTable();
          this.visibleObject.deleteVisible = false;
        }
      }, (error: HttpErrorResponse) => {

      });
  }

  onEdit(data): void {
    this.editData = data;
    this.mode = 'edit';
    this.visibleObject.formVisible = true;
    this.fileList = [
      {
        uid: '0',
        name: this.editData.imageUrl,
        status: 'done',
        url: this.getImageUrl(this.editData.imageUrl)
      }
    ];
    this.deviceInstanceForm.patchValue(this.editData);
  }

  handleChange(info: NzUploadChangeParam): void {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1); // 限制只上传一张图片

    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      this.deviceInstanceForm.patchValue({imageUrl: info.file.response});
    } else if (info.file.status === 'error') {
      // this.msg.error(`${info.file.name} file upload failed.`);
    }

    this.fileList = fileList;
  }

  getExtraData(file: NzUploadFile): any {
    return {
      multipartFiles: file
    };
  }

  handleSubmit(): void {
    if (this.deviceInstanceForm.valid) {
      let {code, name, deviceDefId, model, imageUrl} = this.deviceInstanceForm.value;
      const {siteId} = this.currentParams;
      console.log(imageUrl);
      if (this.mode === 'create') {
        imageUrl = imageUrl.join('');
        this.http.createDeviceInstance({code, name, deviceDefId, model, imageUrl, siteId}).subscribe(
          (response) => {
            this.loadTable();
            this.deviceInstanceForm.reset();
            this.fileList = [];
          }, (error: HttpErrorResponse) => {
            this.deviceInstanceForm.reset();
          }
        );
      } else {
        if (typeof (imageUrl) === 'object') {
          imageUrl = imageUrl.join('');
        }
        this.http.updateDeviceInstance({code, name, deviceDefId, model, imageUrl, id: this.editData.id}).subscribe(
          (response) => {
            if (response.code === 0) {
              this.loadTable();
              this.deviceInstanceForm.reset();
              this.fileList = [];
            }
          }, (error: HttpErrorResponse) => {
            this.deviceInstanceForm.reset();
          });
      }


      this.visibleObject.formVisible = false;

    }
  }

  loadTable(): void {
    const {start, size} = this.pagination;
    const keyword = this.currentParams.attrId ? this.currentParams.attrId : '';
    this.http.queryDeviceInstance({
      start: start - 1,
      size,
      keyword,
      sizeId: this.currentParams.siteId
    }).subscribe(
      (res) => {
        if (res.code === 0) {
          this.tableData = res.data.content;
          this.pagination.total = res.data.totalElements;
          this.loading = false;
        }
      }, (err: HttpErrorResponse) => {
        this.loading = false;
        this.tableData = [];
      });
  }

  getAllLineData(): void {
    this.http.getAllLine().subscribe((response) => {
      const currentNode = [];
      for (let line of response.data) {
        currentNode.push({
          title: line.lineName,
          key: line.id,
          type: 'line'
        });
      }
      this.nodes = currentNode;
    }, () => {
    });
  }

  loadNodes(node): Promise<NzTreeNodeOptions[]> {
    return new Promise(resolve => {
      setTimeout(() => {
        if (node.origin.type === 'line') {
          this.http.getSiteByLineId(node.origin.key).subscribe(
            (response) => {
              const newSiteOptions = [];
              for (let site of response.data) {
                newSiteOptions.push({
                  title: site.siteName,
                  key: site.id,
                  type: 'site'
                });
              }
              resolve(newSiteOptions);
            }, () => {
            }
          );
        } else if (node.origin.type === 'site') {
          this.http.getAllDeviceDef().subscribe(
            (response) => {
              const newAttrOptions = [];
              for (let attr of response.data) {
                newAttrOptions.push({
                  title: attr.name,
                  key: attr.id,
                  type: 'attr',
                  isLeaf: true
                });
              }
              resolve(newAttrOptions);
            }, () => {
            }
          );
        }
      }, 1500);

    });
  }

  nzEvent(event: NzFormatEmitEvent): void {
    const node = event.node;
    if (event.eventName === 'expand') {

      if (node?.getChildren().length === 0 && node?.isExpanded) {
        this.loadNodes(node).then(data => {
          node.addChildren(data);
        });
      }
    } else if (event.eventName === 'click') {
      if (node.origin.type === 'site') {
        this.currentParams.siteId = node.origin.key;
        this.currentParams.attrId = null;
      } else if (node.origin.type === 'attr') {
        this.currentParams.attrId = node.origin.key;
        this.currentParams.siteId = node.parentNode.origin.key;
        this.deviceInstanceForm.patchValue({deviceDefId: node.origin.key});
      }
      this.loadTable();
      console.log(this.currentParams);
    }

  }

  ngOnInit(): void {
    this.getAllLineData();
    this.http.getAllDeviceDef().subscribe((response) => {
      if (response.code === 0) {
        this.deviceDefAllData = response.data;
      }
    }, () => {
    });
    this.deviceInstanceForm = this.fb.group({
      name: [null, Validators.required],
      code: [null, Validators.required],
      deviceDefId: [null, Validators.required],
      model: [null, Validators.required],
      imageUrl: [null]
    });
  }
}
